//
//  UpdateAddressViewController.swift
//  WangPu
//
//  Created by xiaozhi on 15/10/23.
//  Copyright © 2015年 zhixiao. All rights reserved.
//

import UIKit
enum UpdateType{
    case Add,Edited
}
class UpdateAddressViewController: BaseViewController {
    var type:UpdateType = UpdateType.Edited
    var address:AddressListItem?
    var addBtn:UIButton!
    var bottomView:UIView!
    var nameField:UITextField!
    var phoneField:UITextField!
    var mainAddressField:UITextField!
    var detailAddressField:UITextField!
    var currentField:UITextField?
    var areaPickView:AreaPickView?
    var currentProviceObj:ProviceObj?
    var currentCityObj:CityObj?
    var curretnDistrictObj:DistrictObj?
    override func viewDidLoad() {
        super.viewDidLoad()
        self.title = "地址管理"
        let backItem = UIBarButtonItem(image: UIImage(named: "back_icon"), style:UIBarButtonItemStyle.Plain, target:self, action:"goBack")
        backItem.tintColor = UIColor.whiteColor()
        self.navigationItem.leftBarButtonItem = backItem
        self.automaticallyAdjustsScrollViewInsets = false
        view.backgroundColor = commonBackgoundColor
        if type == UpdateType.Edited{
            let rightItem = UIBarButtonItem(image: UIImage(named: "top--del"), style:UIBarButtonItemStyle.Plain, target:self, action:"delete")
            rightItem.tintColor = UIColor.whiteColor()
            self.navigationItem.rightBarButtonItem = rightItem
        }
        self.setupViews()
        self.setupBottomView()
        // Do any additional setup after loading the view.
    }
    func setupBottomView(){
        bottomView = UIView(frame: CGRectMake(0, view.bounds.size.height-49, view.bounds.size.width, 49))
        view.addSubview(bottomView)
        //背景
        let line = UIImageView(frame: CGRectMake(0, 0, bottomView.bounds.size.width, onePix))
        line.backgroundColor = commonRedColor
        bottomView.addSubview(line)
        //新建
        addBtn = UIButton(frame: CGRectMake(20,5, bottomView.bounds.size.width - 40, bottomView.bounds.size.height-10))
        addBtn.setTitleColor(UIColor.whiteColor(), forState: UIControlState.Normal)
        if type == UpdateType.Edited{
            addBtn.setTitle("保存", forState: UIControlState.Normal)
        }
        else{
            addBtn.setTitle("提交", forState: UIControlState.Normal)
        }
        
        addBtn.backgroundColor = commonRedColor
        addBtn.addTarget(self, action: "addBtnClick:", forControlEvents: UIControlEvents.TouchUpInside)
        addBtn.layer.cornerRadius = 4.0
        addBtn.titleLabel?.font = UIFont.systemFontOfSize(15)
        bottomView.addSubview(addBtn)
        
    }

    func  goBack(){
        self.navigationController?.popViewControllerAnimated(true)
    }
    func setupViews()->Void{
        //收货人
        //receiver-icon1
        let baseHieght:CGFloat = 40.0
        let labelX:CGFloat = 32.0
        let offsetX:CGFloat = 10.0
        let line1 = LineView(frame: CGRectMake(0, 74, view.bounds.size.width, baseHieght))
        let userImgView = UIImageView(frame: CGRectMake(offsetX, (line1.bounds.size.height-16)/2.0, 16, 16))
        userImgView.image = UIImage(named: "receiver-icon1")
        line1.addSubview(userImgView)
        let note1 = UILabel(frame: CGRectMake(labelX, 0, 75, baseHieght))
        note1.text = "收货人："
        note1.font = UIFont.systemFontOfSize(14)
        line1.addSubview(note1)
        nameField = UITextField(frame: CGRectMake(CGRectGetMaxX(note1.frame), 0, line1.bounds.size.width - CGRectGetMaxX(note1.frame), baseHieght))
        nameField.borderStyle = UITextBorderStyle.None
        nameField.placeholder = "请填写收货人姓名"
        nameField.font = UIFont.systemFontOfSize(14)
        nameField.delegate = self
        line1.addSubview(nameField)
        view.addSubview(line1)
        //联系方式
       // phone-icon2
        let line2 = LineView(frame: CGRectMake(0, CGRectGetMaxY(line1.frame), view.bounds.size.width, baseHieght))
        let phoneImgView = UIImageView(frame: CGRectMake(offsetX, (line2.bounds.size.height-16)/2.0, 16, 16))
        phoneImgView.image = UIImage(named: "phone-icon2")
        line2.addSubview(phoneImgView)
        let note2 = UILabel(frame: CGRectMake(labelX, 0, 75, baseHieght))
        note2.text = "联系方式："
        note2.font = UIFont.systemFontOfSize(14)
        line2.addSubview(note2)
        phoneField = UITextField(frame: CGRectMake(CGRectGetMaxX(note1.frame), 0, line1.bounds.size.width - CGRectGetMaxX(note1.frame), baseHieght))
        phoneField.borderStyle = UITextBorderStyle.None
        phoneField.placeholder = "请填写手机号码"
        phoneField.font = UIFont.systemFontOfSize(14)
        phoneField.delegate = self
        line2.addSubview(phoneField)
        view.addSubview(line2)
        //address
        //location
        let line3 = LineView(frame: CGRectMake(0, CGRectGetMaxY(line2.frame), view.bounds.size.width, baseHieght*2))
        let locationImgView = UIImageView(frame: CGRectMake(offsetX+2, (line3.bounds.size.height-16)/2.0, 13, 17))
        locationImgView.image = UIImage(named: "location")
        line3.addSubview(locationImgView)
        let line4 = LineView(frame: CGRectMake(labelX, 0, line3.bounds.size.width-labelX, baseHieght))
        let note3 = UILabel(frame: CGRectMake(0, 0, 75, baseHieght))
        note3.text = "所在地区："
        note3.font = UIFont.systemFontOfSize(14)
        line4.addSubview(note3)
        mainAddressField = UITextField(frame: CGRectMake(CGRectGetMaxX(note3.frame), 0, line4.bounds.size.width - CGRectGetMaxX(note3.frame)-20, baseHieght))
        mainAddressField.borderStyle = UITextBorderStyle.None
        mainAddressField.userInteractionEnabled = false
        mainAddressField.placeholder = "请选择地区"
        mainAddressField.font = UIFont.systemFontOfSize(14)
        mainAddressField.delegate = self
        line4.addSubview(mainAddressField)
        let accssImgView = UIImageView(frame: CGRectMake(line4.bounds.size.width-16, (line4.bounds.size.height-12)/2.0, 6, 11))
        accssImgView.image = UIImage(named: "forward_icon")
        line4.addSubview(accssImgView)
        let button = UIButton(frame: line4.bounds)
        button.addTarget(self, action: "showAreaView", forControlEvents: UIControlEvents.TouchUpInside)
        line4.addSubview(button)
        line3.addSubview(line4)
        
        
        let line5 = LineView(frame: CGRectMake(labelX, baseHieght, line3.bounds.size.width-labelX, baseHieght))
        let note4 = UILabel(frame: CGRectMake(0, 0, 75, baseHieght))
        note4.text = "详细地址："
        note4.font = UIFont.systemFontOfSize(14)
        line5.addSubview(note4)
        detailAddressField = UITextField(frame: CGRectMake(CGRectGetMaxX(note3.frame), 0, line5.bounds.size.width - CGRectGetMaxX(note4.frame), baseHieght))
        detailAddressField.borderStyle = UITextBorderStyle.None
        detailAddressField.placeholder = "请填写详细地址"
        detailAddressField.font = UIFont.systemFontOfSize(14)
        detailAddressField.delegate = self
        line5.addSubview(detailAddressField)
        line3.addSubview(line5)
        view.addSubview(line3)
        
        if type == UpdateType.Edited{
            nameField.text = address?.username
            phoneField.text = address?.telephone
            if let st = address?.content{
                let str = st as NSString
                let array:[String] = str.componentsSeparatedByString(" ")
                if array.count == 7{
                    mainAddressField.text = array[1] + array[2] + array[3]
                    detailAddressField.text = array[4]
                }
                else if array.count == 6{
                    mainAddressField.text = array[1] + array[2]
                    detailAddressField.text = array[3]
                }
            }
        }

    }
    override func viewDidAppear(animated: Bool) {
        super.viewDidAppear(animated)
        if areaPickView == nil{
            areaPickView = NSBundle.mainBundle().loadNibNamed("AreaPickView", owner: self, options: nil)[0] as? AreaPickView
            areaPickView!.frame = self.view.bounds
            areaPickView?.hidden = true
            areaPickView?.setArea = { [weak self] info1,info2,info3 in
                self?.currentProviceObj = info1
                self?.currentCityObj = info2
                self?.curretnDistrictObj = info3
                if info1 != nil{
                    self?.mainAddressField.text = info1!.name!
                }
                if info2 != nil && info1!.name != info2!.name{
                    self?.mainAddressField.text = self!.mainAddressField.text! + info2!.name!
                }
                if info3 != nil{
                    self?.mainAddressField.text = self!.mainAddressField.text! + info3!.name!
                }
            }
            view.addSubview(areaPickView!)
        }
    }
    func  delete(){
        if #available(iOS 8.0, *) {
            let alertController = UIAlertController(title: "是否确认删除该地址", message: "", preferredStyle: UIAlertControllerStyle.ActionSheet)
            let deleteAction = UIAlertAction(title: "删除", style: UIAlertActionStyle.Destructive){ action in
                let request = NetWorkHelper()
                let parameters = NSMutableDictionary()
                parameters.setObject(GlobalDataHelper.instance.session!, forKey: "sessionid")
                 parameters.setObject(self.address!.id!, forKey: "id")
                request.requestStart("/address/delete", parameters: parameters,compeleteHandle:{ (data, response, error)  in
                    dispatch_async(dispatch_get_main_queue()){
                        self.hiddenProcessView()
                    }
                    if error == nil{
                        var dic:NSDictionary?
                        do {
                            dic = try NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.AllowFragments) as? NSDictionary
                        } catch let error as NSError {
                            print(error)
                        }
                        if (dic?["result"])! as! String == "0"{
                            dispatch_async(dispatch_get_main_queue()){
                                self.showTips("删除成功"){
                                    self.navigationController?.popViewControllerAnimated(true)
                                }
                            }
                        }
                        
                    }
                    else{
                        dispatch_async(dispatch_get_main_queue()){
                            self.showTips("删除失败")
                        }
                        
                    }
                })
                self.showProcess("处理中...")
                
            }
            let cancelAction = UIAlertAction(title: "取消", style: UIAlertActionStyle.Cancel, handler: nil)
            
            alertController.addAction(cancelAction)
            alertController.addAction(deleteAction)
            self.presentViewController(alertController, animated: true, completion: nil)
        } else {
            // Fallback on earlier versions
        }
    }
    func  showAreaView(){
        currentField?.resignFirstResponder()
        areaPickView!.showPickView()
    }
    @IBAction func addBtnClick(button:UIButton){
        //姓名
        
        if let name = self.nameField.text{
           let nameinfo = name.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceCharacterSet()) as NSString
            if nameinfo.length == 0{
                self.showTips("收货人不能为空")
                return
            }
        }
        else{
            self.showTips("收货人不能为空")
            return
        }
        if !phoneField.text!.isValidPhoneNumber(){
            self.showTips("请输入正确手机号码")
            return
        }
        //处理地址填写情况
        if self.mainAddressField.text == nil || self.mainAddressField.text == ""{
            self.showTips("您还未选择地区")
            return
        }
        if let name = self.detailAddressField.text{
            let nameinfo = name.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceCharacterSet()) as NSString
            if nameinfo.length == 0{
                self.showTips("请填写详细地址")
                return
            }
        }
        else{
            self.showTips("请填写详细地址")
            return
        }
        let request = NetWorkHelper()
        let parameters = NSMutableDictionary()
        parameters.setObject(GlobalDataHelper.instance.session!, forKey: "sessionid")
        parameters.setObject(nameField.text!, forKey: "cn_name")
        if self.currentProviceObj != nil{
            parameters.setObject(self.currentProviceObj!.code!, forKey: "cn_province")
        }
        else{
            parameters.setObject(self.address!.cn_province!, forKey: "cn_province")
  
        }
        if self.currentCityObj != nil{
            parameters.setObject(self.currentCityObj!.code!, forKey: "cn_city")
        }
        else{
            parameters.setObject(self.address!.cn_city!, forKey: "cn_city")
        }
        if self.curretnDistrictObj != nil{
            parameters.setObject(self.curretnDistrictObj!.code!, forKey: "cn_district")
            parameters.setObject(self.curretnDistrictObj!.zip_code!, forKey: "postcode")

        }
        else{
            if self.currentCityObj != nil{
                parameters.setObject(self.currentCityObj!.zip_code!, forKey: "postcode")
                parameters.setObject("", forKey: "cn_district")

            }
            else{
                parameters.setObject(self.address!.postCode!, forKey: "postcode")
                parameters.setObject(self.address!.cn_district!, forKey: "cn_district")

 
            }
        }
        parameters.setObject(detailAddressField.text!, forKey: "street")
        parameters.setObject(phoneField.text!, forKey: "telephone")
        parameters.setObject("CN", forKey: "country_id")
        if type == UpdateType.Add{
            parameters.setObject("0", forKey: "id")
        }
        else{
            print(address!.id!)
            parameters.setObject(address!.id!, forKey: "id")
        }
        request.requestStart("/address/update", parameters: parameters,compeleteHandle:{ (data, response, error)  in
            dispatch_async(dispatch_get_main_queue()){
                self.hiddenProcessView()
            }
            if error == nil{
                var dic:NSDictionary?
                do {
                    dic = try NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.AllowFragments) as? NSDictionary
                } catch let error as NSError {
                    print(error)
                    dispatch_async(dispatch_get_main_queue()){
                        self.showTips("数据加载出错")
                    }
                    return
                }
                if (dic?["result"])! as! String == "0"{
                    dispatch_async(dispatch_get_main_queue()){
                        if self.type == UpdateType.Add{
                            self.showTips("添加成功"){
                                self.navigationController?.popViewControllerAnimated(true)

                            }
                        }
                        else{
                            self.showTips("修改成功"){
                                self.navigationController?.popViewControllerAnimated(true)

                            }
                        }
                    }
                }
                
            }
            else{
                dispatch_async(dispatch_get_main_queue()){
                    if self.type == UpdateType.Add {
                        self.showTips("添加失败")
                    }
                    else{
                        self.showTips("修改失败")
                    }
                }
            }
        })
        self.showProcess("处理中...")
    }
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    

    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
        // Get the new view controller using segue.destinationViewController.
        // Pass the selected object to the new view controller.
    }
    */

}
extension UpdateAddressViewController:UITextFieldDelegate{
    func textFieldDidBeginEditing(textField: UITextField){
        currentField = textField
    }
    func textFieldShouldReturn(textField: UITextField) -> Bool {
        textField.resignFirstResponder()
        return true
    }
}